<template>
  <a-modal
    :open="visible"
    :title="isEdit ? '编辑用户' : '添加用户'"
    :confirm-loading="loading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    width="600px"
    destroy-on-close
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      layout="vertical"
      :label-col="{ span: 24 }"
      :wrapper-col="{ span: 24 }"
    >
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="用户账号" name="userAccount">
            <a-input
              v-model:value="formData.userAccount"
              placeholder="请输入用户账号"
              :disabled="isEdit"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="用户昵称" name="userName">
            <a-input v-model:value="formData.userName" placeholder="请输入用户昵称" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="用户角色" name="userRole">
            <a-select v-model:value="formData.userRole" placeholder="请选择用户角色">
              <a-select-option value="user">普通用户</a-select-option>
              <a-select-option value="admin">管理员</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="生日" name="birthday">
            <a-date-picker
              v-model:value="formData.birthday"
              placeholder="请选择生日"
              style="width: 100%"
              format="YYYY-MM-DD"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="邮箱" name="userEmail">
            <a-input v-model:value="formData.userEmail" placeholder="请输入邮箱" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="手机号" name="userPhone">
            <a-input v-model:value="formData.userPhone" placeholder="请输入手机号" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="头像URL" name="userAvatar">
        <a-input v-model:value="formData.userAvatar" placeholder="请输入头像URL" />
      </a-form-item>

      <a-form-item label="用户简介" name="userProfile">
        <a-textarea v-model:value="formData.userProfile" placeholder="请输入用户简介" :rows="3" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import dayjs, { type Dayjs } from 'dayjs'
import { userApi } from '@/api/user'
import type { UserVO, UserAddRequest, UserUpdateRequest } from '@/types/user'

interface Props {
  visible: boolean
  userData: UserVO | null
  isEdit: boolean
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const loading = ref(false)
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive<{
  userAccount: string
  userName: string
  userRole: 'user' | 'admin'
  userEmail: string
  userPhone: string
  userAvatar: string
  userProfile: string
  birthday: Dayjs | null
}>({
  userAccount: '',
  userName: '',
  userRole: 'user',
  userEmail: '',
  userPhone: '',
  userAvatar: '',
  userProfile: '',
  birthday: null,
})

// 表单验证规则
const formRules = {
  userAccount: [
    { required: true, message: '请输入用户账号', trigger: 'blur' },
    { min: 6, max: 16, message: '账号长度应为6-16位', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]+$/, message: '账号只能包含字母和数字', trigger: 'blur' },
  ],
  userName: [{ max: 50, message: '昵称长度不能超过50位', trigger: 'blur' }],
  userRole: [{ required: true, message: '请选择用户角色', trigger: 'change' }],
  userEmail: [{ type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }],
  userPhone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }],
  userProfile: [{ max: 500, message: '简介长度不能超过500位', trigger: 'blur' }],
}

// 监听弹窗显示状态
watch(
  () => props.visible,
  (visible) => {
    if (visible && props.userData) {
      // 编辑模式，填充表单数据
      Object.assign(formData, {
        userAccount: props.userData.userAccount || '',
        userName: props.userData.userName || '',
        userRole: props.userData.userRole || 'user',
        userEmail: props.userData.userEmail || '',
        userPhone: props.userData.userPhone || '',
        userAvatar: props.userData.userAvatar || '',
        userProfile: props.userData.userProfile || '',
        // 处理 LocalDate 格式的生日 (YYYY-MM-DD)
        birthday: props.userData.birthday ? dayjs(props.userData.birthday, 'YYYY-MM-DD') : null,
      })
    } else if (visible && !props.userData) {
      // 添加模式，重置表单
      resetForm()
    }
  },
)

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    userAccount: '',
    userName: '',
    userRole: 'user',
    userEmail: '',
    userPhone: '',
    userAvatar: '',
    userProfile: '',
    birthday: null,
  })
  formRef.value?.resetFields()
}

// 处理提交
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    loading.value = true

    if (props.isEdit && props.userData) {
      // 编辑用户
      const updateData: UserUpdateRequest = {
        id: props.userData.id,
        userName: formData.userName,
        userRole: formData.userRole,
        userEmail: formData.userEmail,
        userPhone: formData.userPhone,
        userAvatar: formData.userAvatar,
        userProfile: formData.userProfile,
        birthday: formData.birthday ? formData.birthday.format('YYYY-MM-DD') : undefined,
      }
      await userApi.updateUser(updateData)
      message.success('更新用户成功')
    } else {
      // 添加用户
      const addData: UserAddRequest = {
        userAccount: formData.userAccount,
        userName: formData.userName,
        userRole: formData.userRole,
        userEmail: formData.userEmail,
        userPhone: formData.userPhone,
        userAvatar: formData.userAvatar,
        userProfile: formData.userProfile,
        birthday: formData.birthday ? formData.birthday.format('YYYY-MM-DD') : undefined,
      }
      await userApi.addUser(addData)
      message.success('添加用户成功')
    }

    emit('success')
  } catch (error) {
    console.error('操作失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理取消
const handleCancel = () => {
  emit('update:visible', false)
  resetForm()
}
</script>

<style scoped>
:deep(.ant-form-item-label > label) {
  font-weight: 500;
}
</style>
